import React from 'react'
import wx from 'weixin-js-sdk'
import history from '../../history'
import { get } from '../../axios'

export const wechatShareHOC = WrappedComponent => {
    return  class WechatShare extends React.Component {
                constructor(props) {
                    super(props)
                    this.state = {
                        config: {},
                        share: {
                            title: '标题', // 分享标题
                            desc: '描述！', // 分享描述
                            link: location.origin+`?invite_id=`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                            imgUrl: location.origin + '/lips_share.jpg', // 分享图标
                        }
                    }
                }

                componentDidMount() {
                    console.log(WrappedComponent)
                    this.initialWxConifg()
                    
                    // window.addEventListener('popstate', ()=> {
                    //     console.log('url pop change')
                    //     this.initialWxConifg()
                    // });
                    history.listen((location, action) => {
                        console.log(action, location.pathname, location.state)
                        this.initialWxConifg()
                    })
                   
                }

                initialWxConifg() {
                    let url = window.location.href,
                        { share } = this.state
                    
                    get(`/mem/wechat-share?url=${encodeURIComponent(url)}`)
                    .then(json => {
                        // this.setState({config: {...json, debug: true}}) 
                        wx.config({...json, debug: true})  
                        wx.ready(() => {
                            //分享给朋友
                              wx.onMenuShareAppMessage(share)
    
                              //分享到朋友圈
                              wx.onMenuShareTimeline(share)
    
                        })                     
                    })
                    .catch(e=>console.log(e))
                }

                render () {
                    return <WrappedComponent {...this.props} />
                }
            }
}
